package com.lkd.config.file;

import com.lkd.config.MinIOConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class FileManager {

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinIOConfig minIOConfig;

    /**
     * minio 上传 方法
     * @param file
     * @return
     */
    public String uploadFile(MultipartFile file) throws Exception {

//        获取后缀  123.jpg
        String suffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
//        创建新的文件名字,不能重复  xxxx.jpg
        String newFileName  = UUID.randomUUID().toString() +"." + suffix;
//       上传的参数
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(newFileName)//对象名字
                .bucket(minIOConfig.getBucket())//桶的名字
                .contentType(file.getContentType())//对象类型
                .stream(file.getInputStream(),file.getSize(),-1)//对象流
                .build();
//        使用client上传对象
        minioClient.putObject(putObjectArgs);
        StrBuilder strBuilder = new StrBuilder(minIOConfig.getReadPath());
        strBuilder.append("/").append(minIOConfig.getBucket()).append("/").append(newFileName);

        log.info("上传文件路径={}",strBuilder.toString());

        return strBuilder.toString();

    }

}
